<?php

namespace App\Http\Controllers\Api;

use App\CouponCode;
use App\Files;
use App\GameUserInfo;
use App\Http\Services\Aes;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\YunPian;
use App\Images;
use App\QrCodes;
use App\User;
use App\UserInfo;
use App\UserIntegralRecord;
use App\UserScore;
use App\UserScoreRank;
use App\UserScoreRecord;
use App\UserShareFriend;
use App\UserTotoalScore;
use App\VerifyPhone;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use Cookie;
use Log;
//use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Endroid\QrCode\QrCode;

class GameController extends Controller
{
    public function getInitUrl(Request $request)
    {
//        $url = "https://h5.rzkeji.com/aaa.html";
//        $url = "https://h5.rzkeji.com/bbb.html";
        $url = "https://h5.rzkeji.com/advert.html";
        return response()->json(["level" => "success", "message" => "获取成功", 'data' => $url]);
    }

    //todo 获取验证码
    public function sendGameVerificationCode(Request $request)
    {
        $phone = $request->get('phone');
        $isAttact = VerifyPhone::whereIp($request->ip())->orderBy('created_at', 'desc')->first();
        $isAttact_count = VerifyPhone::whereIp($request->ip())->count();

        if(!preg_match("/^(1[34578])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        if ($isAttact_count > 3 && $isAttact->created_at->timestamp + 60 > time())
            return response()->json(['level' => 'error', 'message' => '请等待60秒后再发送']);
        if ($isAttact_count > 24 && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
            return response()->json(['level' => 'error', 'message' => '不允许访问！']);

        $result = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            return response()->json(['level' => 'error', 'message' => '请等待60秒后再发送']);

        VerifyPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone = new VerifyPhone();
        $VerifyCodeByPhone->phone = $phone;
        $VerifyCodeByPhone->verify_code = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip = $request->ip();
        $VerifyCodeByPhone->ensure_session = '';

        $send = new YunPian();
        $send->sendGameSmsWithCode($phone, $VerifyCodeByPhone->verify_code);

        $VerifyCodeByPhone->save();

        return response()->json(['level' => 'success', 'message' => trans('验证码发送成功')]);
    }

    //todo 手机验证码登录
    public function loginPhoneGame(Request $request){
        $phone      = $request->get('phone');
        $verifyCode = $request->get('verify_code');

        if(is_null($phone))
            return response()->json(['level' => 'error','message' => '手机号不能为空']);

        if(!preg_match("/^(1[34578])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        if(is_null($verifyCode))
            return response()->json(['level' => 'error','message' => '验证码不能为空']);

        /** @var VerifyPhone $verifyCodeByPhone */
        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verifyCode)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);
        }
        $verifyCodeByPhone -> delete();

        /** @var User $thisUser */
        $thisUser = User::wherePhone($phone)->first();
        if(!$thisUser){
            $thisUser = new User();
            $thisUser->phone = $phone;
            $thisUser->user_key=md5("123456".time());
            $thisUser->save();

            $thisUserInfo = new UserInfo();
            $thisUserInfo->user_id    = $thisUser->id;
            $thisUserInfo->sex        = rand(0,1);
            if($thisUserInfo->sex == 1){
                $thisUserInfo->photo_id = rand([5812,5814,5816,5817,5818,5819]);
            }elseif($thisUserInfo->sex == 0){
                $thisUserInfo->photo_id = rand([5822,5823,5824,5825]);
            }
            $thisUserInfo->nickname  = substr($phone,0,3)."******".substr($phone,9,2);
            $thisUserInfo->save();
        }


        $token = CryptoJSAES::encrypt($thisUser->user_key,env('AES_KEY'));
        $cookie = Cookie::forever("user_token",$token);

        return response()->json(['level' => 'success','message' => '登录成功','data' => $token,'user_key' => $thisUser->user_key])->cookie($cookie);
    }

    //todo 登录游戏
    public function loginGame(Request $request)
    {

        $user_key = $request->get('user_key');
        $shareUserId = $request->get('share_user_id');

        Log::error("gameA===>" . $shareUserId);
        Log::error("aaaaaa");

        /** @var User $user */
        $user = User::whereUserKey($user_key)->first();
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先授权!', 'data' => 'no_login']);

        /** @var UserInfo $userInfo */
        $userInfo = UserInfo::whereUserId($user->id)->first();
        if (!$userInfo)
            return response()->json(['level' => 'error', 'message' => '没有用户信息!', 'data' => 'no_user_info']);

        $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);

        if(!is_null($user->phone) && $user->phone != ''){
            $is_phone = 1;
        }else{
            $is_phone = 0;
        }

        if ($shareUserId > 0) {
            // 生成两条
            $newFriend = new UserShareFriend();
            $newFriend->share_user_id = $shareUserId;
            $newFriend->invited_user_id = $user->id;
            $newFriend->save();

            $myFriend = new UserShareFriend();
            $myFriend->share_user_id = $user->id;
            $myFriend->invited_user_id = $shareUserId;
            $myFriend->save();
        }

        return response()->json(["level" => "success", "message" => "登录成功", 'data' => $userInfo,'is_phone' => $is_phone]);
    }

//TODO 绑定手机号
    public function gameBindingPhone(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先授权!', 'data' => 'no_login']);

        $phone = $request->get('phone');

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请输入手机号吗']);

        if(!preg_match("/^(1[34578])[0-9]{9}$/", trim($phone)))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        /** @var User $isPhone */
        $isPhone = User::wherePhone($phone)->where("wx_openid","like","olD5O5%")->first();
        if($isPhone && $user->id != $isPhone->id)
            return response()->json(['level' => 'error','message' => '该手机号已被注册']);

        $user->phone = $phone;
        $user->save();

        return response()->json(['level' => 'success','message' => '绑定成功','data' => $user]);
    }

    /**
     * 设置游戏身份信息接口
     * @param Request $request
     * @return mixed
     */
    public function setGameUserInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先授权!', 'data' => 'no_login']);

        $realName = $request->get('real_name');
        $phone    = $request->get('phone');
        $address  = $request->get('address');
        $idCard   = $request->get('id_card');

        if(is_null($realName) || $realName == '')
            return response()->json(['level' => 'error','message' => '请填写姓名']);

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(!preg_match("/^(1[34578])[0-9]{9}$/", trim($phone)))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        if(is_null($address) || $address == '')
            return response()->json(['level' => 'error','message' => '请填写地址信息']);

        if(is_null($idCard) || trim($idCard) == '')
            return response()->json(['level' => 'error','message' => '请填写身份证号']);

        if(!preg_match("/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/",trim($idCard)))
            return response()->json(['level' => 'error','message' => '身份证号格式错误']);

        $newGameUserInfo = GameUserInfo::whereUserId($user->id)->first();
        if(!$newGameUserInfo)
            $newGameUserInfo = new GameUserInfo();

        $newGameUserInfo->user_id                    = $user->id;
        $newGameUserInfo->real_name                  = $realName;
        $newGameUserInfo->phone                      = $phone;
        $newGameUserInfo->address                    = $address;
        $newGameUserInfo->id_card                    = $idCard;
        $newGameUserInfo->save();

        return response()->json(['level' => 'success','message' => '已收到您的资料，请尽快与客服联系，感谢您的参与','data' => $newGameUserInfo]);
    }

    /**
     * 身份信息不存在
     * @param Request $request
     * @return mixed
     */
    public function getGameUserInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先授权!', 'data' => 'no_login']);

        $thisGameUserInfo = GameUserInfo::whereUserId($user->id)->first();
        if(!$thisGameUserInfo)
            return response()->json(['level' => 'error','message' => '身份信息不存在']);

        $user->game_user_info = $thisGameUserInfo;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $user]);
    }

// todo 开始游戏
    public function startGame(Request $request)
    {

        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0, 0, 0, $tm, $td, $ty);
        $todayEndTime = mktime(23, 59, 59, $tm, $td, $ty);


        /** @var UserTotoalScore 今天的游戏记录 $game */
        $game = UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->orderBy('created_at', 'desc')->first();

        if (!$game) {
            $game = new UserTotoalScore();
            $game->user_id = $user->id;
            $game->game_time = 2;
            /* 游戏次数*/
            $game->status = 1;
            $game->save();

            $gameRecord = new UserScoreRecord();
            $gameRecord->user_id = $user->id;
            $gameRecord->score = 0;
            $gameRecord->gold_num = 0;
            $gameRecord->type = "game";
            $gameRecord->status = 1;
            $gameRecord->save();
        } else {

            /** @var UserScoreRecord 单局游戏的记录,是否可以继续游戏 $gameRecord */
            $gameRecord = UserScoreRecord::whereUserId($user->id)->whereType('game')->whereStatus(1)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->first();
            if (!$gameRecord) {
                if ($game->game_time == 0) {
                    return response()->json(['level' => 'error', 'message' => '今天你已经GG了三次，请扫码复活或者分享复活继续玩游戏!', 'data' => 'no_share_time']);
                }

                $game->game_time = $game->game_time - 1;
                $game->save();

                $gameRecord = new UserScoreRecord();

                $gameRecord->user_id = $user->id;
                $gameRecord->type = "game";
                $gameRecord->score = 0;
                $gameRecord->gold_num = 0;
                $gameRecord->status = 1;
                $gameRecord->save();
            }
        }

        //计算用户的分数
        $thatUserScore = UserScore::whereUserId($user->id)->first();
        if($thatUserScore){
            $goldNumCount = UserScoreRecord::whereUserId($user->id)->sum("gold_num");
            $scoreCount = UserScoreRecord::whereUserId($user->id)->where("type","<>","exchange")->sum("score");
            $exchangeScoreCount = UserScoreRecord::whereUserId($user->id)->whereType("exchange")->sum("score");

            $thatUserScore->gold_num = $goldNumCount;
            $thatUserScore->score = (int)$scoreCount - (int)$exchangeScoreCount;
            $thatUserScore->save();
        }

        return response()->json(['level' => 'success', "message" => "开始游戏", 'data' => $gameRecord]);
    }


    //todo 复活游戏
    public function relive(Request $request)
    {

        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);
        /*     $user=User::whereId(8)->first();*/

        //** 不固定死 */
        $type = $request->get('type');
        $scanQKey = $request->get('scan_q_key');
        /*       $score=$request->get('score');
               $gold_num=$request->get('gold_num');*/


        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0, 0, 0, $tm, $td, $ty);
        $todayEndTime = mktime(23, 59, 59, $tm, $td, $ty);

        /*        $game=UserScoreRecord::whereId($user->id)->whereStatus(1)->whereType('game')->first();
                if($game)
                    return response()->json(['level' => 'error','message' => '你还有未结束的游戏，无需复活了!','data'=>'no_game']);*/

        $game = UserScoreRecord::whereType('game')->whereUserId($user->id)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->orderBy('created_at', 'desc')->first();
        if (!$game)
            return response()->json(['level' => 'error', 'message' => '今天你还未开始游戏哦!', 'data' => 'no_game']);


        $theUserScore = UserScore::whereUserId($user->id)->whereBetween('created_at', ["2019-05-28 00:00:00", "2019-06-15 23:59:59"])->first();
        if(!$theUserScore){
            $theUserScore = new UserScore();
            $theUserScore->user_id = $user->id;
//            $theUserScore->game_time = 2;
            $theUserScore->save();
        }

        //TODO 扫码复活
        if ($type == "scan_relive") {

            /** @var QrCodes $isScanQKey */
            $isScanQKey = QrCodes::whereQKey($scanQKey)->whereType('gs')->whereIsUse(0)->first();
            if (!$isScanQKey)
                return response()->json(['level' => 'error', 'message' => '无效二维码!', 'data' => 'is_use']);


            $isScanQKey->is_use = 1;
            $isScanQKey->use_time = date('Y-m-d H-i-s', time());
            $isScanQKey->save();

            $gameAllScore = UserTotoalScore::whereUserId($user->id)->orderBy('created_at', 'desc')->first();
            if (!$gameAllScore)
                return response()->json(['level' => 'error', 'message' => '找不到游戏记录!', 'data' => 'no_game_record']);

            $gameAllScore->score = (int)$gameAllScore->score + 3300;
            $gameAllScore->gold_num = (int)$gameAllScore->gold_num + 30;
            $gameAllScore->relive_time = (int)$gameAllScore->relive_time + 1;
            $gameAllScore->save();

            $game->status = 1;
            $game->save();


            $newScanRecord = new  UserScoreRecord();
            $newScanRecord->user_id = $user->id;
            if (!is_null($type)) $newScanRecord->type = $type;

            $newScanRecord->score = 3300;
            $newScanRecord->gold_num = 30;
            $newScanRecord->remark = "扫码复活";

            $newScanRecord->save();

            $theUserScore->score = $theUserScore->score + 3300;
            $theUserScore->gold_num = $theUserScore->gold_num + 30;
            $theUserScore->save();

            $message = "复活成功" . "+" . "300" . "积分";

        } //TODO 转发复活
        else {

            $shareRecord = UserScoreRecord::whereUserId($user->id)->whereType('share_relive')->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->get();

            if (count($shareRecord) < 10) {

                /** @var UserTotoalScore $gameAllScore */
                $gameAllScore = UserTotoalScore::whereUserId($user->id)->orderBy('created_at', 'desc')->first();
                if (!$gameAllScore)
                    return response()->json(['level' => 'error', 'message' => '找不到游戏记录!', 'data' => 'no_game_record']);

                $gameAllScore->score = (int)$gameAllScore->score + 30;
                $gameAllScore->gold_num = (int)$gameAllScore->gold_num + 3;
                $gameAllScore->relive_time = (int)$gameAllScore->relive_time + 1;
                $gameAllScore->save();


                $game->status = 1;
                $game->save();

                $newShareRecord = new UserScoreRecord();
                $newShareRecord->user_id = $user->id;
                if (!is_null($type)) $newShareRecord->type = $type;

                $newShareRecord->score = 30;

                $newShareRecord->gold_num = 3;
                $newShareRecord->remark = "分享复活";
                $newShareRecord->save();
                $message = "复活成功" . "+" . "30" . "积分";

                $theUserScore->score = $theUserScore->score + 30;
                $theUserScore->gold_num = $theUserScore->gold_num + 3;
                $theUserScore->save();

            } else {

                return response()->json(['level' => 'error', 'message' => '今天的分享复活次数已经用完!', 'no_share_time']);

            }

        }
        return response()->json(["level" => "success", "message" => $message, 'data' => $game]);
    }


//todo 记录游戏、复活
    public function record(Request $request)
    {

        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);


        $type     = $request->get('type');
        $score    = !is_null($request->get('score')) ? $request->get('score') : 0;
        $gold_num = !is_null($request->get('gold_num')) ? $request->get('gold_num') : 0;
        $weight   = !is_null($request->get('weight')) ? $request->get('weight') : 666;
        $speed    = !is_null($request->get('speed')) ? $request->get('speed') : 0;


        //解密的代码
        $newAes = new Aes("bf0cd6a8c4fe549f","pkcs7","1234567890123456");
        $theScore   = $newAes->decrypt($score);
        $theGoldNum = $newAes->decrypt($gold_num);

        Log::error("score==>".$theScore);
        Log::error("goldnum==>".$theGoldNum);
        if(!$score || !$theGoldNum){
            return response()->json(['level' => 'error', 'message' => '恶意刷分将取消活动资格!']);
        }

        if(strpos($theScore,'nidaye#') === false || strpos($theScore,'nidaye#') === false){
            return response()->json(['level' => 'error', 'message' => '恶意刷分将取消活动资格!']);
        }

        $score    = intval(str_replace('#nidaye#','',$theScore));
        $gold_num = intval(str_replace('nidaye#','',$theGoldNum));

        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0, 0, 0, $tm, $td, $ty);
        $todayEndTime = mktime(23, 59, 59, $tm, $td, $ty);

        /** @var UserTotoalScore $allScore */
        $allScore = UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->first();


        $message = "";
        $newRecord = "";

        if (!$allScore) {
            $allScore = new UserTotoalScore();
            $allScore->user_id = $user->id;
            $allScore->game_time = 2;
            $allScore->status = 1;
            $allScore->save();
        }

        $theUserScore = UserScore::whereUserId($user->id)->whereBetween('created_at', ["2019-05-28 00:00:00", "2019-06-15 23:59:59"])->first();
        if(!$theUserScore){
            $theUserScore = new UserScore();
            $theUserScore->user_id = $user->id;
            $theUserScore->game_time = 2;
            $theUserScore->save();
        }

        //TODO 记录游戏分数
        if ($type == "game") {

            /** @var UserScoreRecord $newRecord */
            $newRecord = UserScoreRecord::whereUserId($user->id)->whereType('game')->whereStatus(1)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->first();
            if (!$newRecord) {

                $message = "获得游戏" . $score . "积分";
                $newRecord = new UserScoreRecord();
                $newRecord->remark = "游戏积分";
                $newRecord->user_id = $user->id;
                /*                $newRecord->relive_time=0;*/
                $newRecord->status = 0;
                $newRecord->speed = 0;
                /** 游戏记录为0：死亡状态 */
                if (!is_null($type)) $newRecord->type = $type;
                if (!is_null($score)) $newRecord->score = (int)$score;
                if (!is_null($gold_num)) $newRecord->gold_num = (int)$gold_num;
                $newRecord->save();

                $allScore->gold_num = (int)$allScore->gold_num + (int)$gold_num;
                $allScore->score = (int)$allScore->score + (int)$score;
                $allScore->save();

                $theUserScore->gold_num = (int)$theUserScore->gold_num + (int)$gold_num;
                $theUserScore->score = (int)$theUserScore->score + (int)$score;
                $theUserScore->save();

            } else {
                if ($newRecord->weight > 0) {
                    $addScore = (int)$score - (int)$newRecord->score;
                    $addGoldNum = (int)$gold_num - (int)$newRecord->gold_num;

                    $message = "获得游戏" . $score . "积分";
                    $newRecord->remark = "游戏积分";
                    $newRecord->user_id = $user->id;
                    $newRecord->status = 0;
                    $newRecord->speed = 0;
                    /** 游戏记录为0：死亡状态 */
                    $newRecord->weight = 0;
                    if (!is_null($type)) $newRecord->type = $type;
                    if (!is_null($score)) $newRecord->score = (int)$score;
                    if (!is_null($gold_num)) $newRecord->gold_num = (int)$gold_num;
                    $newRecord->save();


                    $allScore->gold_num = (int)$allScore->gold_num + (int)$addGoldNum;
                    $allScore->score = (int)$allScore->score + (int)$addScore;
                    $allScore->save();

                    $theUserScore->gold_num = (int)$theUserScore->gold_num + (int)$addGoldNum;
                    $theUserScore->score = (int)$theUserScore->score + (int)$addScore;
                    $theUserScore->save();
                } else {

                    $message = "获得游戏" . $score . "积分";

                    $addScore = (int)$score - (int)$newRecord->score;
                    $addGoldNum = (int)$gold_num - (int)$newRecord->gold_num;


                    $newRecord->status = 0;
                    $newRecord->speed = 0;
                    /** 游戏记录为0：死亡状态 */
                    $newRecord->user_id = $user->id;
                    /*                $newRecord->relive_time=$newRecord->relive_time+1;*/
                    if (!is_null($type)) $newRecord->type = "game";
                    if (!is_null($score)) $newRecord->score = (int)$score;
                    if (!is_null($gold_num)) $newRecord->gold_num = (int)$gold_num;
                    $newRecord->remark = "游戏积分";
                    $newRecord->save();

                    $allScore->gold_num = (int)$allScore->gold_num + (int)$addGoldNum;
                    $allScore->score = (int)$allScore->score + (int)$addScore;
                    $allScore->save();

                    $theUserScore->gold_num = (int)$theUserScore->gold_num + (int)$addGoldNum;
                    $theUserScore->score = (int)$theUserScore->score + (int)$addScore;
                    $theUserScore->save();
                }

            }
        }
        if ($type == "stop_game") {
            $newRecord = UserScoreRecord::whereUserId($user->id)->whereType('game')->whereStatus(1)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->first();
            if (!$newRecord)
                $newRecord = new UserScoreRecord();
            $newRecord->status = 1;
            /** 游戏记录为1：未死状态 */
            $message = "暂停成功";
            $newRecord->remark = "游戏积分";
            $newRecord->user_id = $user->id;
            $newRecord->relive_time = 0;
            $newRecord->weight = (int)$weight;
            $newRecord->speed  = $speed;
            if (!is_null($type)) $newRecord->type = "game";
            if (!is_null($score)) $newRecord->score = (int)$score;
            if (!is_null($gold_num)) $newRecord->gold_num = (int)$gold_num;
            $newRecord->save();
        }


        if ($type == "exchange") {

            $allScore = UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [date('Y-m-d H:i:s', $todayStartTime), date('Y-m-d H:i:s', $todayEndTime)])->first();
            if ($allScore < $score)
                return response()->json(['level' => 'error', 'message' => '积分不足，不能兑换!', 'data' => 'no_full_score']);

            $exchange = UserScoreRecord::whereUserId($user->id)->whereType('exchange')->first();
            if ($exchange)
                return response()->json(['level' => 'error', 'message' => '只能兑换一次奖品!', 'data' => 'is_exchanged']);

            $message = "兑换扣除" . $score . "积分";

            $newRecord = new UserScoreRecord();

            $newRecord->user_id = $user->id;
            if (!is_null($type)) $newRecord->type = $type;
            if (!is_null($score)) $newRecord->score = (int)$score;
            if (!is_null($gold_num)) $newRecord->gold_num = (int)$gold_num;
            $newRecord->remark = "兑换积分";
            $newRecord->save();


//            $allScore->gold_num = (int)$gold_num;
            $allScore->score = (int)$allScore->score - (int)$score;
            $allScore->save();

//            $theUserScore->gold_num = (int)$gold_num;
            $theUserScore->score = (int)$theUserScore->score >= (int)$score ? (int)$theUserScore->score - (int)$score : 0;
            $theUserScore->save();
        }


        return response()->json(["level" => "success", "message" => $message, "data" => $newRecord]);

    }

    //todo 判断是不是前三名或四到三十六名
    public function getRanking(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);
        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time    = $gamaDateCycle['start_time'];
        $end_time      = $gamaDateCycle['end_time'];
        $type          = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';

        if($type == 'Top_three'){
            /** @var UserScore $allUserScore */
            $allUserScores = UserScoreRank::whereUserId($user->id)->first();
            //前三名
//            $qiansanming = array();
//            if(count($allUserScores) > 0){
//                foreach($allUserScores as $key=>$allUserScore){
//                    if($key <= 2){
//                        array_push($qiansanming,$allUserScore->user_id);
//                    }
//                }
//            }

            if(!$allUserScores || ($allUserScores && $allUserScores->rank > 3))
                return response()->json(['level' => 'error','message' => '您不是前三名哦']);

            $isGameUserInfo = GameUserInfo::whereUserId($user->id)->first();
            if(!$isGameUserInfo)
                return response()->json(['level' => 'error','message' => '请完善身份信息','no_game_user_info']);

        }elseif($type == 'top_four'){
            /** @var UserScore $allUserScore */
            $allUserScores = UserScoreRank::whereUserId($user->id)->first();
            //四至三十六名
//            $sidaosanshiliu = array();
//            if(count($allUserScores) > 0){
//                foreach($allUserScores as $key=>$allUserScore){
//                    if($key >= 3 && $key <= 35){
//                        array_push($sidaosanshiliu,$allUserScore->user_id);
//                    }
//                }
//            }

            if(!$allUserScores || ($allUserScores && $allUserScores->rank > 42) || ($allUserScores && $allUserScores->rank < 4))
                return response()->json(['level' => 'error','message' => '您不是4-42名呦']);

//            $isGameUserInfo = GameUserInfo::whereUserId($user->id)->first();
//            if(!$isGameUserInfo)
//                return response()->json(['level' => 'error','message' => '请完善身份信息','no_game_user_info']);
        }elseif($type == 'top_hundred'){
            $todayY = date('Y',time());
            $todayM = date('m',time());
            $todayD = date('d',time());

            $firstToday = mktime(0,0,0,$todayM,$todayD,$todayY);
            $lastToday  = mktime(23,59,59,$todayM,$todayD,$todayY);

            /** @var UserScore $allUserScore */
            $allUserScores = UserScoreRank::whereUserId($user->id)->first();
            //前100名
//            $beforeHundred = array();
//            if(count($allUserScores) > 0){
//                foreach($allUserScores as $key=>$allUserScore){
//                    if($key <= 99){
//                        array_push($beforeHundred,$allUserScore->user_id);
//                    }
//                }
//            }

            if(!$allUserScores)
                return response()->json(['level' => 'error','message' => '您今日还不是前100名哦！']);

        }elseif($type == 'default'){
            /** @var UserScore $thisUserScores */
            $thisUserScores = UserScore::whereUserId($user->id)->whereBetween('created_at', ["2019-05-17 00:00:00", "2019-05-29 00:00:00"])->first();
            if($thisUserScores && $thisUserScores->score < 21000)
                return  response()->json(['level' => 'error','message' => '您的积分还没达到21000，继续努力哦']);
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }

        if($type == 'top_hundred'){
            $couponCode=CouponCode::whereUserId($user->id)->whereIsUse(1)->whereType("you")->first();
            if($couponCode){
                return response()->json(['level' => 'success','message' => '成功进入','data' => $couponCode]);
            }else{
                return response()->json(['level' => 'success', 'message' => '成功进入!']);

            }
        }elseif($type == 'default'){
            $couponCode=CouponCode::whereUserId($user->id)->whereIsUse(1)->whereType("super")->first();
            if($couponCode){
                return response()->json(['level' => 'success','message' => '成功进入','data' => $couponCode]);
            }else{
                return response()->json(['level' => 'success', 'message' => '成功进入!']);

            }
        }else{
            return response()->json(['level' => 'success', 'message' => '成功进入!']);
        }
    }

    public function getRecord(Request $request)
    {
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        /*       $user=User::whereId(6)->first();*/
        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];
        $type = !is_null($request->get('type')) ? $request->get('type') : "all";
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 4;
        $page = $request->get('page');

        $gameRecords = [];

        if ($type != "me") {
            $allUserRecores = UserScore::whereNotIn("user_id",[782,761,895,876])->whereBetween('created_at', [$start_time, $end_time])->orderBy("score", "desc")->offset(($page - 1) * $limit)->limit($limit)->get();
            if (count($allUserRecores) > 0) {
                foreach ($allUserRecores as $key => $allUserRecore) {
                    $gameRecord = [];
                    /** @var UserScore $allUserRecore */
                    $userInfo = UserInfo::whereUserId($allUserRecore->user_id)->first();
                    $gameRecord['user_photo_url'] = FileManager::getImgUrl($userInfo ? $userInfo->photo_id : 0);
                    $gameRecord['user_nick_name'] = $userInfo ? $userInfo->nickname : "玩家";
                    $gameRecord['rank'] = ($page - 1) * 5 + $key + 1;
                    $gameRecord['relive_time'] = 0;
                    $gameRecord['friend_rank'] = 1;

                    if ($allUserRecore->user_id == $user->id) {
                        $gameRecord['user_nick_name'] = "自己";
                    }

                    $gameRecord['score'] = $allUserRecore->score;
                    $gameRecord['gold_num'] = $allUserRecore->gold_num;
                    $gameRecord['relive_time'] = $allUserRecore->relive_time;
                    array_push($gameRecords, $gameRecord);
                }
            }
        }


        if ($type == "me") {

            //todo 朋友圈排名  勿删除
            $allFriendsId = UserShareFriend::whereShareUserId($user->id)->pluck("invited_user_id")->toArray();

            array_push($allFriendsId, $user->id);
            $allFriendsId = array_unique($allFriendsId);

            $friendScores = UserScore::whereIn("user_id",$allFriendsId)->whereBetween('created_at', ['2019-05-17 00:00:00', '2019-05-29 00:00:00'])->orderBy("score","desc")->get();
            $allScores = UserScore::whereNotIn("user_id",[782,761,895,876])->whereBetween('created_at', ['2019-05-17 00:00:00', '2019-05-29 00:00:00'])->orderBy("score","desc")->get();

//            $frank = 1;
//            $rank  = 1;

            $thatUserScore = null;
            if(count($friendScores) > 0){
                foreach ($friendScores as $key=>$friendScore){
                    if($friendScore->user_id == $user->id){
                        $thatUserScore = $friendScore;
                        $frank = $key + 1;
                        $thatUserScore["friend_rank"] = $frank;
                        break;
                    }
                }
            }

            if(count($allScores) > 0){
                foreach ($allScores as $key=>$allScore){
                    if($allScore->user_id == $user->id){
                        if(!$thatUserScore){
                            $thatUserScore = $allScore;
                        }
                        $rank = $key + 1;
                        $thatUserScore["rank"] = $rank;
                        break;
                    }
                }
            }

            if(!is_null($thatUserScore)){
                $theUserScoreRecord = UserScoreRecord::whereUserId($user->id)->orderBy("score","desc")->first();
                $theUserScore = UserScore::whereUserId($user->id)->first();
                $thatUserScore["score"] = $theUserScore ? $theUserScore->score : 0;
            }

            if(is_null($thatUserScore)){
                $thatUserScore["rank"] = 0;
                $thatUserScore["friend_rank"] = 0;
                $thatUserScore["score"] = 0;
                $thatUserScore["gold_num"] = 0;
                $thatUserScore["relive_time"] = 0;
            }

            $thatUserScoreRank = UserScoreRank::whereUserId($user->id)->first();
            if($thatUserScoreRank){
                $thatUserScore["score"] = $thatUserScoreRank->score;
                $thatUserScore["gold_num"] = $thatUserScoreRank->gold_num;
                $thatUserScore["rank"] = $thatUserScoreRank->rank;
            }

//            $myRank = DB::table('user_score')->select("score","count(*) AS QUANTITY")->groupBy("score")->orderBy("QUANTITY","desc");
//            $allFriendsRecord = [];
//            if (count($allFriendsId) > 0) {
//                foreach ($allFriendsId as $item) {
//                    $friendRecord = [];
//                    $friendRecord['user_id'] = $item;
//                    $friendRecord['friend_rank'] = 1;
//                    $gameUserScore = UserScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->first();
//                    $friendRecord['score'] = $gameUserScore->score;
//                    array_push($allFriendsRecord, $friendRecord);
//
//                }
//            }
//            if (count($allFriendsRecord) > 0) {
//
//                $i = 0;
//                $myFriendRank = [];
//                foreach ($allFriendsRecord as $friendRecord) {
//                    $allFriendsRecord[$i]['rank'] = $i + 1;
//                    if ($friendRecord['user_id'] == $user->id) {
//                        $myFriendRank = $allFriendsRecord[$i];
//                    }
//                    $i++;
//                }
//
//
//                $my['friend_rank'] = $myFriendRank['rank'];
//
//            }
//
//            $gameRecords = $my;

            $gameRecords = $thatUserScore;
        }

        return response()->json(["level" => "success", "message" => '获取成功', "data" => $gameRecords]);
    }

    public function getRecordLast(Request $request)
    {
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        /*       $user=User::whereId(6)->first();*/
        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];
        $type = !is_null($request->get('type')) ? $request->get('type') : "all";
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 4;
        $page = $request->get('page');

        $gameRecords = [];

        if ($type != "me") {
            $allUserRecores = UserScoreRank::all();
            if (count($allUserRecores) > 0) {
                foreach ($allUserRecores as $key => $allUserRecore) {
                    $gameRecord = [];
                    /** @var UserScoreRank $allUserRecore */
//                    $userInfo = UserInfo::whereUserId($allUserRecore->user_id)->first();
                    $gameRecord['user_photo_url'] = FileManager::getImgUrl($allUserRecore->photo_id);
                    $gameRecord['user_nick_name'] = !is_null($allUserRecore->nickname) ? $allUserRecore->nickname : "玩家";
                    $gameRecord['rank'] = $allUserRecore->rank;
                    $gameRecord['relive_time'] = 0;
                    $gameRecord['friend_rank'] = 1;

                    if ($allUserRecore->user_id == $user->id) {
                        $gameRecord['user_nick_name'] = "自己";
                    }

                    $gameRecord['score'] = $allUserRecore->score;
                    $gameRecord['gold_num'] = $allUserRecore->gold_num;
                    array_push($gameRecords, $gameRecord);
                }
            }
        }

        /** @var CouponCode $superCouponCode */
        $superCouponCode = CouponCode::whereUserId($user->id)->whereIsUse(1)->whereType('super')->first();
        if($superCouponCode){
            $superCoupon = $superCouponCode->code_value;
        }else{
            $superCoupon = '';
        }

        /** @var CouponCode $youCouponCode */
        $youCouponCode = CouponCode::whereUserId($user->id)->whereIsUse(1)->whereType('you')->first();
        if($youCouponCode){
            $youCoupon = $youCouponCode->code_value;
        }else{
            $youCoupon = '';
        }

        return response()->json(["level" => "success", "message" => '获取成功', "data" => $gameRecords,'super_coupon_code' => $superCoupon,'you_coupon_code' => $youCoupon]);
    }

// todo 获取游戏全国排行和自己的朋友圈和全国排行
    public function getRecordBack(Request $request)
    {


        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        /*       $user=User::whereId(6)->first();*/
        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];
        $type = !is_null($request->get('type')) ? $request->get('type') : "all";
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 4;
        $page = $request->get('page');

        $gameRecords = [];


        $records = UserTotoalScore::whereBetween('created_at', [$start_time, $end_time])->get();

        $allUserIds = [];
        if (count($records) > 0) {
            foreach ($records as $record) {
                array_push($allUserIds, $record->user_id);
            }
        }
        $allUserId = array_unique($allUserIds);

        if (count($allUserId) > 0) {
            foreach ($allUserId as $item) {

                $gameRecord = [];

                $gameRecord['user_id'] = $item;
                $userInfo = UserInfo::whereUserId($item)->first();
                $gameRecord['user_photo_url'] = FileManager::getImgUrl($userInfo ? $userInfo->photo_id : 0);
                $gameRecord['user_nick_name'] = $userInfo ? $userInfo->nickname : "玩家";
                $gameRecord['rank'] = 0;
                $gameRecord['relive_time'] = 0;
                $gameRecord['friend_rank'] = 1;

                if ($item == $user->id) {
                    $gameRecord['user_nick_name'] = "自己";

                }

                $gameUserScore = 0;
                $gameUserGoldNum = 0;
                $gameUserReliveTime = 0;
//                $gameUserRecords = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->get();
//                foreach ($gameUserRecords as $gameUserRecord) {
//                    $gameUserScore = $gameUserScore + $gameUserRecord->score;
//                    $gameUserGoldNum = $gameUserGoldNum + $gameUserRecord->gold_num;
//                    $gameUserReliveTime = $gameUserReliveTime + $gameUserRecord->relive_time;
//                }

                $gameUserScore = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->sum("score");
                $gameUserGoldNum = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->sum("gold_num");
                $gameUserReliveTime = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->sum("relive_time");
                $gameRecord['score'] = $gameUserScore;
                $gameRecord['gold_num'] = $gameUserGoldNum;
                $gameRecord['relive_time'] = $gameUserReliveTime;
                array_push($gameRecords, $gameRecord);

            }


//TODO 排序
            if (count($gameRecords) > 0) {

                for ($i = 0; $i < count($gameRecords); $i++) {
                    for ($k = 0; $k < $i; $k++) {

                        if ($gameRecords[$i]['score'] > $gameRecords[$k]['score']) {

                            /*              $gameRecords[$i]['rank']=$k+1;
                                          $gameRecords[$k]['rank']=$i+1;*/
                            $temp = $gameRecords[$i];
                            $gameRecords[$i] = $gameRecords[$k];
                            $gameRecords[$k] = $temp;
                        }
                    }
                }

                $i = 0;
                $my = [];
                foreach ($gameRecords as $gameRecord) {
                    $gameRecords[$i]['rank'] = $i + 1;
                    if ($gameRecord['user_id'] == $user->id) {
                        $my = $gameRecords[$i];
                    }
                    $i++;
                }


                if ($type == "me") {

                    //todo 朋友圈排名  勿删除
                    $friends = UserShareFriend::whereShareUserId($user->id)->get();
                    $allFriendsId = [];
                    if (count($friends) > 0) {

                        foreach ($friends as $friend) {
                            array_push($allFriendsId, $friend->invited_user_id);

                        }
                    }


                    array_push($allFriendsId, $user->id);
                    $allFriendsId = array_unique($allFriendsId);

                    $allFriendsRecord = [];
                    if (count($allFriendsId) > 0) {
                        foreach ($allFriendsId as $item) {

                            $friendRecord = [];

                            $friendRecord['user_id'] = $item;
                            /*                                   $friendRecord['rank'] = 0;*/
                            $friendRecord['friend_rank'] = 1;

                            $gameUserScore = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->sum("score");;
//                            $gameUserRecords = UserTotoalScore::whereUserId($item)->whereBetween('created_at', [$start_time, $end_time])->get();
//                            foreach ($gameUserRecords as $gameUserRecord) {
//                                $gameUserScore = $gameUserScore + $gameUserRecord->score;
//                            }

                            $friendRecord['score'] = $gameUserScore;
                            array_push($allFriendsRecord, $friendRecord);

                        }
                    }
                    if (count($allFriendsRecord) > 0) {

                        for ($i = 0; $i < count($allFriendsRecord); $i++) {
                            for ($k = 0; $k < $i; $k++) {

                                if ($allFriendsRecord[$i]['score'] > $allFriendsRecord[$k]['score']) {

                                    /*
                                              $allFriendsRecord[$i]['friend_rank']=$k+1;
                                              $allFriendsRecord[$k]['friend_rank']=$i+1;*/

                                    $temp = $allFriendsRecord[$i];
                                    $allFriendsRecord[$i] = $allFriendsRecord[$k];
                                    $allFriendsRecord[$k] = $temp;
                                }
                            }
                        }

                        $i = 0;
                        $myFriendRank = [];
                        foreach ($allFriendsRecord as $friendRecord) {
                            $allFriendsRecord[$i]['rank'] = $i + 1;
                            if ($friendRecord['user_id'] == $user->id) {
                                $myFriendRank = $allFriendsRecord[$i];
                            }
                            $i++;
                        }


                        $my['friend_rank'] = $myFriendRank['rank'];

                    }

                    $gameRecords = $my;
                }

//                if ($type == "all") {
//
//                    $gameRecords = array_slice($gameRecords, 0, 100);
//
//                    if ($page > 0 && $page == 1) {
//
//                        $gameRecords = array_slice($gameRecords, $limit * ($page - 1), $limit);
//                        if ($my && !is_null($my['rank'])) {
//                            if ($my['rank'] > $limit - 1) {
//                                $gameRecords[$limit - 1] = $my;
//                            }
//                        }
//
//                    }
//
//                    if ($page > 1) {
//
//
//                        if ($my && !is_null($my['rank'])) {
//                            if (($my['rank'] < $limit + 1) && $page == 2) {
//                                $gameRecords = array_slice($gameRecords, $limit * ($page - 1), $limit);
//                            } else {
//                                $gameRecords = array_slice($gameRecords, $limit * ($page - 1) - 1, $limit);
//                            }
//
//
//                        } else {
//
//
//                            if ($page == 2) {
//                                $gameRecords = array_slice($gameRecords, $limit * ($page - 1), $limit);
//                            } else {
//                                $gameRecords = array_slice($gameRecords, $limit * ($page - 1) - 1, $limit);
//                            }
//
//
//                        }
//
//                    }
//
//                }


            }

        }


        return response()->json(["level" => "success", "message" => '获取成功', "data" => $gameRecords]);

    }

    public function gameTimeCycle(Request $request)
    {


        /*     $nowTime=strtotime(date('2019-4-9 00:00:00'));*/

        $nowTime = time();
        $startTime = strtotime(date('2019-5-28 00:00:00'));
        $b = 12 * 86400;

        $a = $nowTime - $startTime;

        for ($i = 0; $a > $b; $i++) {
            $a = $a - $b;
        }


        $gameStartTime = $startTime + ($i * $b);
        $endTime = $startTime + ($i + 1) * $b - 1;

        $startDate = date("Y-m-d H:i:s", $gameStartTime);
        $endDate = date("Y-m-d H:i:s", $endTime);

        $data['start_time'] = $startDate;
        $data['end_time'] = $endDate;

        return $data;

        /*      $statDate=date("Y-m-d H:i:s",$gameStartTime);
              $endDate=date("Y-m-d H:i:s",$endTime);
              dd($endTime,"+",$gameStartTime,"+",$statDate,"+",$endDate);
      */

    }


    public function appletCode(Request $request)
    {


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf9f00414b59cdc29&secret=25856b6cebfdd5312f5061259a63ede1";
        $access_token = $this->get_access_token($url);
        $scene = 'uid=6';
        var_dump($access_token);

        /*        $page="pages/gameHome/main";*/

        $page = "pages/contentHome/main";
        $data = array();
        $data['page'] = $page;
        $data['scene'] = $scene;
        $data = json_encode($data);
        $access = json_decode($access_token, true);
        $access_token = $access['access_token'];
        $to_url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $da = $this->api_notice_increment($to_url, $data);

        /*        var_dump($da);*/

        $path = './1.png';
        $config = config('code');
        file_put_contents($path, $da);

        $path = $config['img_path'];
        $download_file_name = "f6" . '.png';
        $file_name = $path . $download_file_name;
        file_put_contents($file_name, $da);


    }

    public function image(Request $request)
    {

        if (!$request->hasFile('image'))
            return '文件不存在';
        $image_info = $_FILES['image'];

        $image_path = $image_info['tmp_name'];


        $base64_image = $this->getImageBase64($image_path);
        $image = $base64_image;

        return $image;

    }


    public function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = array("Accept-Charset: utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        } else {

            return $tmpInfo;
        }
    }


    public function get_access_token($url)
    {

        return $data = $this->curl_get($url);
    }


    function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        return $data;
    }


    public static function getImageBase64($image_path)
    {

        /*        $image_info = getimagesize($image_path);*/
        $image_data = fread(fopen($image_path, 'r'), filesize($image_path));
        /*        $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));*/
        $base64_image = chunk_split(base64_encode($image_data));
        return $base64_image;

    }

    public function setTemplate(Request $request)
    {


        $form_id = $request->get('form_id');
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];

        $date = date('Y=m-d H:i:s', time());


//        $allScore = UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [$start_time,$end_time])->get();
//
//        $gameScore=0;
//        if(count($allScore)>0){
//            foreach($allScore as $item){
//                $gameScore=$gameScore + $item->score;
//            }
//        }

        $gameScore = UserScore::whereUserId($user->id)->whereBetween("created_at",["2019-05-17 00:00:00","2019-05-28 23:59:59"])->sum("score");

        if ($gameScore < 21000 )
            return response()->json(['level' => 'error', 'message' => '积分不足，不能兑换!', 'data' => 'no_full_score']);


        /** @var UserScoreRecord $exchange */
//        $exchange = UserScoreRecord::whereUserId($user->id)->whereType('exchange')->whereBetween('created_at', [$start_time,$end_time])->first();
        $exchange = UserScoreRecord::whereUserId($user->id)->whereType('exchange')->first();

        if ($exchange&& $user->id!=87)
            return response()->json(['level' => 'error', 'message' => '你已经兑换过一次奖品，下次再来!', 'data' => 'is_exchanged']);

        $couponCode=CouponCode::whereIsUse(0)->whereType("super")->orderBy('created_at','asc')->first();
        if(!$couponCode)
            return response()->json(['level' => 'error', 'message' => '奖品已经兑换完了，下次再来!', 'data' => 'is_exchanged']);


        $openId = $user->wx_openid;

      /*  $userInfo = UserInfo::whereUserId($user->id)->first();
        if (!$userInfo)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => '请完善用户信息']);*/

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf9f00414b59cdc29&secret=25856b6cebfdd5312f5061259a63ede1";
        $access_token = $this->get_access_token($url);
        if($access_token){
            $access = json_decode($access_token, true);
            $access_token = $access['access_token'];
        }else{
            return response()->json(['level' => 'error', 'message' => '请求失败!']);
        }




        $data = ([
            'access_token'=>$access_token,
            'touser' => $openId,
            'template_id' => "eDT5t_pBa9hylEY3gpSYt5GX8_F8nJJ_TqMx7rMPlIA",
            'form_id' => $form_id,
            'page'=>"pages/contentTep/main?code_value=".$couponCode->code_value,

            'data' => [

                "keyword1" => [
                    "value" => "F6高膳食纤维饮品抵用券",
                    "color" => '#173177'
                ],
                "keyword2" => [
                    "value" => "2019.5.17-2019.6.19",
                    "color" => '#173177'
                ],
                "keyword3" => [
                    "value" => "六角兽饮料有限公司",
                    "color" => '#173177'
                ],
                "keyword4" => [
                    "value" => date("Y-m-d H:i:s",time()),
                    "color" => '#173177'
                ],
            ]
        ]);

        $to_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;

        $result = json_decode($this->https_curl_json($to_url,$data,'json'));

//        Log::error("aaaaaa".printf($result,true));
        if($result){

//             Log::error("bbbbbb".printf($result,true));

            if($result->errmsg=="ok"){
                $newRecord = new UserScoreRecord();
                $newRecord->user_id = $user->id;
                $newRecord->type ="exchange";
                $newRecord->score = 21000;
                $newRecord->remark = "兑换积分";
                $newRecord->save();



                /** @var UserTotoalScore $dayScore */
                $dayScore =UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [$start_time,$end_time])->first();
                $dayScore->score=$dayScore->score-21000;
                $dayScore->save();



/*                log::error("ssss");*/
//                $imgId=self::getQrcodeUrl($couponCode->code_vaule,$request);
//
                $couponCode->is_use=1;
                $couponCode->used_time=date('Y-m-d H:i:s',time());
                $couponCode->user_id=$user->id;
//                $couponCode->img_id=$imgId;
                $couponCode->save();


                return response()->json(["level" => "success", "message" => '领取成功，请返回微信并在“服务通知”中查看','data'=>$couponCode]);

            }else{
                return response()->json(['level' => 'error', 'message' => '数据异常','data'=>$result->errmsg]);
            }



            /*            echo json_encode(array('state'=>5,'msg'=>$result));*/
        }

        else{
            return response()->json(['level' => 'error', 'message' => '请求失败!']);
        }
    }

    public function JudgeIntegral(Request $request){
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        /*计算游戏活动周期*/
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];

        $date = date('Y=m-d H:i:s', time());


        $allScore = UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [$start_time,$end_time])->get();

        $gameScore=0;
        if(count($allScore)>0){
            foreach($allScore as $item){
                $gameScore=$gameScore + $item->score;
            }
        }
        if ($gameScore < 21000 )
            return response()->json(['level' => 'error', 'message' => '积分不足，不能兑换!', 'data' => 'no_full_score']);


        /** @var UserScoreRecord $exchange */
        $exchange = UserScoreRecord::whereUserId($user->id)->whereType('exchange')->first();
//        $exchange = UserScoreRecord::whereUserId($user->id)->whereType('exchange')->whereBetween('created_at', [$start_time,$end_time])->first();

        if ($exchange)
            return response()->json(['level' => 'error', 'message' => '你已经兑换过一次奖品，下次再来!', 'data' => 'is_exchanged']);

        /** @var CouponCode $couponCode */
        $couponCode=CouponCode::whereIsUse(0)->whereType("super")->orderBy('id','asc')->first();
        if(!$couponCode)
            return response()->json(['level' => 'error', 'message' => '奖品已经兑换完了，下次再来!', 'data' => 'is_exchanged']);

        $newRecord = new UserScoreRecord();
        $newRecord->user_id = $user->id;
        $newRecord->type ="exchange";
        $newRecord->score = 21000;
        $newRecord->remark = "兑换积分";
        $newRecord->save();


        $thatUserScore = UserScore::whereUserId($user->id)->first();
        if($thatUserScore){
            $thatUserScore->score = $thatUserScore->score - 21000;
            $thatUserScore->save();
        }

        /** @var UserTotoalScore $dayScore */
        $dayScore =UserTotoalScore::whereUserId($user->id)->whereBetween('created_at', [$start_time,$end_time])->first();
        $dayScore->score=$dayScore->score-21000;
        $dayScore->save();



        /*                log::error("ssss");*/
//                $imgId=self::getQrcodeUrl($couponCode->code_vaule,$request);
//
        $couponCode->is_use=1;
        $couponCode->used_time=date('Y-m-d H:i:s',time());
        $couponCode->user_id=$user->id;
//                $couponCode->img_id=$imgId;
        $couponCode->save();


        return response()->json(["level" => "success", "message" => '领取成功，请返回微信并在“服务通知”中查看','data'=>$couponCode]);

    }

    public function getQrcodeByCode(Request $request){
        $code_value=$request->get('code_value');
        $qrcodeCode=CouponCode::whereCodeValue($code_value)->whereIsUse(1)->first();
        if(!$qrcodeCode)
            return response()->json(['level' => 'error', 'message' => '券不存在!']);

        $qrcodeCode->photo_url = route("Api.game.docQrcode")."?code_value=".$code_value;

        return response()->json(["level" => "success", "message" => '获取成功','data'=>$qrcodeCode]);

    }

    public function getH5QrcodeByCode(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var CouponCode $qrCodeCode */
        $qrCodeCode = CouponCode::whereUserId($user->id)->whereIsUse(1)->first();
        if(!$qrCodeCode)
            return response()->json(['level' => 'error', 'message' => '券不存在!']);

        $qrCodeCode->photo_url = route('Api.game.docQrcode').'?code_value='.$qrCodeCode->code_value;

        return response()->json(['level' => 'success','message' => '获取成功','data' => $qrCodeCode]);
    }


    public function https_curl_json($url, $data, $type){
        if ($type == 'json') {//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
            $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
            $data = json_encode($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        return $output;
    }


    public  function  getQrcode(Request $request){

        $code_value=1111;

        $aa=self::getQrcodeUrl($code_value,$request);

        return $aa;

    }

    public static function getQrcodeUrl($code_value,Request $request){
        $login_url=$code_value;

        $data['url']=$login_url;
/*        $data_qrcode =\SimpleSoftwareIO\QrCode\Facades\QrCode::format('png')->size(300)->color(255,0,255)->backgroundColor(255,255,0.45098)->merge('/public/images/zhang.jpg',.15)->generate($login_url);*/
        $data_qrcode =QrCode::format('png')->size(300)->generate($login_url);

        $base64 = base64_encode($data_qrcode);

        $qrcode_base64="data:image/png;base64,".$base64;
        $request->offsetSet('base_code',$qrcode_base64);

        $obj = new ImageController($request);
        $newImage=$obj->uploadBase64ImageFace($request);

        return $newImage->id;
    }

    public function docQrcode(Request $request){
        $code_value = $request->get("code_value");

        $qrCode = new QrCode();
        $qrCode
            ->setText($code_value)
            ->setSize(250)
            ->setPadding(10)
            ->setErrorCorrection('high')
            ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
            ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
            ->setImageType(QrCode::IMAGE_TYPE_PNG)
        ;

        // now we can directly output the qrcode
        header('Content-Type: '.$qrCode->getContentType());
        $qrCode->render();

        // or create a response object
        $response = new Response($qrCode->get(), 200, ['Content-Type' => $qrCode->getContentType()]);

        return $response;
    }

    public function getEverydayScore(Request $request){
        $gamaDateCycle = $this->gameTimeCycle($request);
        $start_time = $gamaDateCycle['start_time'];
        $end_time = $gamaDateCycle['end_time'];

        $gameRecords = [];
        $records = UserTotoalScore::whereBetween('created_at', [$start_time, $end_time])->get();

        $allUserIds = [];
        if (count($records) > 0) {
            foreach ($records as $record) {
                array_push($allUserIds, $record->user_id);
            }
        }
        $allUserId = array_unique($allUserIds);

//        var_dump($allUserId);die;

        if (count($allUserId) > 0) {
            foreach ($allUserId as $item) {
                $gameUserScore = UserTotoalScore::whereUserId((int)$item)->whereBetween('created_at', [$start_time, $end_time])->sum("score");
                $gameRecord['score']   = $gameUserScore;
                $gameRecord['user_id'] = $item;
                if($gameUserScore > 0){
                    array_push($gameRecords, $gameRecord);
                }
            }
        }
        for ($i = 0; $i < count($gameRecords); $i++) {
            for ($k = 0; $k < $i; $k++) {

                if ($gameRecords[$i]['score'] > $gameRecords[$k]['score']) {
                    $temp = $gameRecords[$i];
                    $gameRecords[$i] = $gameRecords[$k];
                    $gameRecords[$k] = $temp;
                }
            }
        }

        for ($j = 0; $j < 100 && $j < count($gameRecords); $j++) {
            $theUserId = $gameRecords[$j]["user_id"];
            $thatUser = User::whereId((int)$theUserId)->first();
            if($thatUser){
                $hasCoupon = CouponCode::whereUserId($thatUser->id)->whereType("you")->first();
                if(!$hasCoupon){
                    /** @var CouponCode $couponCode */
                    $couponCode=CouponCode::whereUserId(0)->whereType("you")->orderBy('id','asc')->first();
                    if($couponCode){
                        $thatCouponCode = CouponCode::whereId($couponCode->id)->first();
                        if($thatCouponCode){
                            $thatCouponCode->user_id = $thatUser->id;
                            $thatCouponCode->save();
                        }

                    }
                }
            }
        }

        echo "complete".$start_time."||".$end_time;
//        var_dump($gameRecords);
    }

    public function getMyYouCoupon(Request $request){
        $user = UserManager::isLogin($request);
        if (!$user)
            return \response()->json(["level"=>"error","message"=>"未登录","data"=>"no_login"]);

        $myYouCoupon = CouponCode::whereUserId($user->id)->whereType("you")->whereIsUse(0)->first();

        if($myYouCoupon){
            return \response()->json(["level"=>"success","message"=>"获取成功","data"=>1]);
        }

        return \response()->json(["level"=>"success","message"=>"获取成功","data"=>0]);
    }

    public function getMyYouCouponMsg(Request $request){
        $form_id = $request->get('form_id');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => 'no_login']);

        $isYouCoupon = CouponCode::whereUserId($user->id)->whereType('you')->whereIsUse(1)->first();
        if($isYouCoupon)
            return response()->json(['level' => 'error','message' => '您已经领取过奖品了！']);

        $myYouCoupon = CouponCode::whereUserId($user->id)->whereType("you")->whereIsUse(0)->first();

        Log::error('aaa=>'.print_r($myYouCoupon,true));
        if(!$myYouCoupon){
            /** @var CouponCode $couponCode */
            $couponCode=CouponCode::whereUserId(0)->whereType("you")->orderBy('id','asc')->first();
            if($couponCode){
                /** @var CouponCode $myYouCoupon */
                $myYouCoupon = CouponCode::whereId($couponCode->id)->first();
                if($myYouCoupon){
                    $myYouCoupon->user_id = $user->id;
                    $myYouCoupon->save();
                }

            }
        }


        $openId = $user->wx_openid;

        /*  $userInfo = UserInfo::whereUserId($user->id)->first();
          if (!$userInfo)
              return response()->json(['level' => 'error', 'message' => '请先登录!', 'data' => '请完善用户信息']);*/

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf9f00414b59cdc29&secret=25856b6cebfdd5312f5061259a63ede1";
        $access_token = $this->get_access_token($url);
        if($access_token){
            $access = json_decode($access_token, true);
            $access_token = $access['access_token'];
        }else{
            return response()->json(['level' => 'error', 'message' => '请求失败!']);
        }




        $data = ([
            'access_token'=>$access_token,
            'touser' => $openId,
            'template_id' => "eDT5t_pBa9hylEY3gpSYt5GX8_F8nJJ_TqMx7rMPlIA",
            'form_id' => $form_id,
            'page'=>"pages/contentTep/main?code_value=".$myYouCoupon->code_value,

            'data' => [

                "keyword1" => [
                    "value" => "F6高膳食纤维饮品抵用券",
                    "color" => '#173177'
                ],
                "keyword2" => [
                    "value" => "2019.5.17-2019.6.19",
                    "color" => '#173177'
                ],
                "keyword3" => [
                    "value" => "六角兽饮料有限公司",
                    "color" => '#173177'
                ],
                "keyword4" => [
                    "value" => date("Y-m-d H:i:s",time()),
                    "color" => '#173177'
                ],
            ]
        ]);

        $to_url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token;

        $result = json_decode($this->https_curl_json($to_url,$data,'json'));
        if($result){

//             Log::error("bbbbbb".printf($result,true));

            if($result->errmsg=="ok"){

//
                $myYouCoupon->is_use=1;
                $myYouCoupon->used_time=date('Y-m-d H:i:s',time());
                $myYouCoupon->user_id=$user->id;
                $myYouCoupon->save();


                return response()->json(["level" => "success", "message" => '领取成功，请返回微信并在“服务通知”中查看','data'=>$myYouCoupon]);

            }else{
                return response()->json(['level' => 'error', 'message' => '数据异常','data'=>$result->errmsg]);
            }
        }else{
            return response()->json(['level' => 'error', 'message' => '请求失败!']);
        }
    }

    public function aesTest(Request $request){
        $a = $request->get("score");

        $newAes = new Aes("bf0cd6a8c4fe549f","pkcs7","1234567890123456");
//        $a = $newAes->encrypt("nidaye#123");
        $b = $newAes->decrypt($a);
//        $b = self::decrypt_pass($a,"bf0cd6a8c4fe549f");

        return response()->json(['level' => 'success', 'message' => '请求成功!',"data"=>$a,"data2"=>$b]);
    }

    //解密
    public static function decrypt_pass($sStr, $sKey) {
        $iv = '1234567890123456';
        $decrypted= mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $sKey,
            base64_decode($sStr),
            MCRYPT_MODE_CBC,
            $iv
        );
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }

    public function rebuildData(){
//        $allScordRecords = UserScoreRecord::whereScore(0)->where("gold_num","<>",0)->whereBetween("created_at",["2019-05-21 00:00:00","2019-05-21 23:59:59"])->get();
//        if(count($allScordRecords) > 0){
//            foreach ($allScordRecords as $allScordRecord){
//                /** @var UserScoreRecord $allScordRecord */
//                $thatUserToalRecord = UserTotoalScore::whereUserId($allScordRecord->user_id)->where("gold_num","<>",0)->whereBetween("created_at",["2019-05-21 00:00:00","2019-05-21 23:59:59"])->first();
//                if($thatUserToalRecord){
//                    /** @var UserTotoalScore $thatUserToalRecord */
//                    $thatUserToalRecord->score = (int)$thatUserToalRecord->score + (int)$allScordRecord->gold_num * 100;
//                    $thatUserToalRecord->save();
//                }
//
//                $thatUserScord = UserScore::whereUserId($allScordRecord->user_id)->first();
//                if($thatUserScord){
//                    $thatUserScord->score = (int)$thatUserScord->score + (int)$allScordRecord->gold_num * 100;
//                    $thatUserScord->save();
//                }
//
//                $allScordRecord->score = (int)$allScordRecord->gold_num * 100;
//                $allScordRecord->save();
//            }
//        }

//        $allUserTotoalScores = UserTotoalScore::all();
//
//        foreach ($allUserTotoalScores as $allUserTotoalScore){
//            /** @var UserTotoalScore $allUserTotoalScore */
//            $hasScore = UserScore::whereUserId($allUserTotoalScore->user_id)->first();
//            if(!$hasScore){
//                $gameUserScore = UserTotoalScore::whereUserId($allUserTotoalScore->user_id)->sum("score");
//                $gameUserGoldNum = UserTotoalScore::whereUserId($allUserTotoalScore->user_id)->sum("gold_num");
//                $gameUserReliveTime = UserTotoalScore::whereUserId($allUserTotoalScore->user_id)->sum("relive_time");
//
//                $newScore = new UserScore();
//                $newScore->score = $gameUserScore;
//                $newScore->gold_num = $gameUserGoldNum;
//                $newScore->relive_time = $gameUserReliveTime;
//                $newScore->user_id     = $allUserTotoalScore->user_id;
//                $newScore->save();
//
//            }else{
//                $gameUserScore      = UserScore::whereUserId($allUserTotoalScore->user_id)->sum("score");
//                $gameUserGoldNum    = UserScore::whereUserId($allUserTotoalScore->user_id)->sum("gold_num");
//                $gameUserReliveTime = UserScore::whereUserId($allUserTotoalScore->user_id)->sum("relive_time");
//
//                $newScore = new UserScore();
//                $newScore->score = $gameUserScore;
//                $newScore->gold_num = $gameUserGoldNum;
//                $newScore->relive_time = $gameUserReliveTime;
//                $newScore->user_id     = $allUserTotoalScore->user_id;
//                $newScore->save();
//            }
//        }

        $allUsers = User::all();
        foreach ($allUsers as $allUser){
            $thatUserScore = UserScore::whereUserId($allUser->id)->first();
            if($thatUserScore){
                $goldNumCount = UserScoreRecord::whereUserId($allUser->id)->sum("gold_num");
                $scoreCount = UserScoreRecord::whereUserId($allUser->id)->where("type","<>","exchange")->sum("score");
                $exchangeScoreCount = UserScoreRecord::whereUserId($allUser->id)->whereType("exchange")->sum("score");

                $thatUserScore->gold_num = $goldNumCount;
                $thatUserScore->score = (int)$scoreCount - (int)$exchangeScoreCount;
                $thatUserScore->save();
            }
        }

//        $allUserScoreRecords = UserScoreRecord::whereType("share_relive")->get();
//        foreach ($allUserScoreRecords as $allUserScoreRecord){
//            if($allUserScoreRecord->score < 300){
//                $allUserScoreRecord->score = 330;
//                $allUserScoreRecord->save();
//            }
//        }

        echo "complete";
    }
}
